package com.xy.tx;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import javax.xml.crypto.Data;

/**
 * @author 谢阳
 * @version 1.8.0_131
 * @date 2022/4/9 16:03
 * @description 环境搭建
 * 1. 导入依赖
 * 数据源、数据库驱动、jdbc
 * 2. 配置数据源、jdbcTemplate
 * 3. 方法上加上@Transactional
 * 4. @EnableTransactionManagement 开启基于事务管理功能
 * 5. 配置事务管理器
 */

@ComponentScan
@Configuration
@PropertySource("classpath:/druid.properties")
@EnableTransactionManagement
public class TxConfig {
    @Value("${druid.driver}")
    private String driver;
    @Value("${druid.url}")
    private String url;
    @Value("${druid.username}")
    private String username;
    @Value("${druid.password}")
    private String password;


    // 数据源
    @Bean
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url + "spring_test");
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }


    // jdbc模板
    @Bean
    public JdbcTemplate jdbcTemplate(DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    @Bean
    public PlatformTransactionManager transactionManager(DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}
